package org.topteam.ui.easyui;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by JiangFeng on 2014/8/7.
 */
public abstract class TagRender extends TagSupport {

    private String id;

    public abstract String getEasyuiTag();

    public abstract int renderBody();

    public abstract Map<String, Object> getOptions();

    public abstract void renderStart(JspWriter out);

    public abstract void renderEnd(JspWriter out);

    public void renderScript(JspWriter out) {

    }

    public boolean isJqueryEventBind(){
        return false;
    }

    public RenderContext getRenderContext() {
        Object o = this.pageContext.getRequest().getAttribute("RenderContext");
        if (o != null) {
            return (RenderContext) o;
        } else {
            return null;
        }
    }

    public String optionsToString() {
        Map<String, Object> optionMap = getOptions();
        if (optionMap == null) {
            return "";
        }
        String options = "";
        for (Iterator<Map.Entry<String, Object>> iterator = optionMap.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, Object> option = iterator.next();
            Object value = option.getValue();
            if (value != null) {
                if (value instanceof Integer) {
                    if ((Integer) value >= 0) {
                        options += "," + option.getKey() + ":" + value;
                    }
                } else if (value instanceof String) {
                    options += "," + option.getKey() + ":'" + value + "'";
                } else if (value instanceof Enum) {
                    options += "," + option.getKey() + ":'" + value + "'";
                } else {
                    options += "," + option.getKey() + ":" + value;
                }
            }
        }
        if (options.length() > 0) {
            options = options.substring(1);
        }
        return options;
    }

    @Override
    public int doStartTag() throws JspException {
        if (getRenderContext() != null) {
            getRenderContext().putTag(this);
        }
        JspWriter out = this.pageContext.getOut();
        renderStart(out);
        return renderBody();
    }

    @Override
    public int doEndTag() throws JspException {
        JspWriter out = this.pageContext.getOut();
        renderEnd(out);
        renderScript(out);
        return Tag.EVAL_PAGE;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
